package com.cjm.juc.wanwenjun;

import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 参见这个类
 * AtomicReferenceTest
 */
public class AtomicReferenceTest {
    private static AtomicStampedReference<Integer> atomicRef = new AtomicStampedReference<>(100, 0);

    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                atomicRef.compareAndSet(100, 101, atomicRef.getStamp(), atomicRef.getStamp()+1);
                System.err.println("after one stamp = :" + atomicRef.getStamp() + ";value = " + atomicRef.getReference());
                TimeUnit.SECONDS.sleep(1);
                atomicRef.compareAndSet(101, 102, atomicRef.getStamp(), atomicRef.getStamp()+1);
                System.err.println("after two stamp = :" + atomicRef.getStamp() + ";value = " + atomicRef.getReference());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "cjm-juc-atomicReference");

        thread.start();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Thread thread1 = new Thread(() -> {
            try {
                int stamp = atomicRef.getStamp();
                TimeUnit.SECONDS.sleep(1);
                atomicRef.compareAndSet(102, 103, stamp, stamp+1);
                System.err.println("after three stamp = " + atomicRef.getStamp() + ";value = " + atomicRef.getReference());
                TimeUnit.SECONDS.sleep(1);
                boolean b = atomicRef.compareAndSet(103, 104, stamp, stamp + 1);
                System.err.println("after four stamp = " + atomicRef.getStamp() + ";value = " + atomicRef.getReference() + ";update success : " + b);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "cjm-juc-atomicReference");

        thread1.start();
    }
}
